package cn.tx.controller;

import cn.tx.config.rabbitmq.DelayedQueueConfig;
import cn.tx.config.rabbitmq.TtlQueueConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

/**
 * https://blog.csdn.net/weixin_43989102/article/details/126276267
 * 访问地址：localhost:8080/ttl/sendMsg/20秒
 * 访问地址：localhost:8080/ttl/sendExpirationMsg/20秒/20000
 * 访问地址：localhost:8080/ttl/sendExpirationMsg/2秒/20000
 * 访问地址：localhost:8080/ttl/sendDelayedMsg/20秒/20000
 * 再访问地址：localhost:8080/ttl/sendDelayedMsg/2秒/2000
 */

@RestController
public class MqSendController {

    private static final Logger logger = LoggerFactory.getLogger(MqSendController.class);

    @Autowired
    private RabbitTemplate rabbitTemplate;


    // 开始发消息
    @GetMapping("/sendMsg/{message}")
    public void sendMsg(@PathVariable String message){
        logger.info("当前时间：{}, 发送一条消息：{} 给两个TTL队列", new Date(), message);
        rabbitTemplate.convertAndSend(TtlQueueConfig.EXC_TTL, "key_ttl_a", "消息来自TTL为 10s 的队列 => "+message);
        rabbitTemplate.convertAndSend(TtlQueueConfig.EXC_TTL, "key_ttl_b", "消息来自TTL为 40s 的队列 => "+message);
    }


    // 开始发消息 消息 TTL
    @GetMapping("/sendExpirationMsg/{message}/{ttlTime}")
    public void sendMsg(@PathVariable String message, @PathVariable String ttlTime){
        logger.info("当前时间：{}, 发送一条时长为 {}ms的消息： {} 给 {} 队列", new Date(), ttlTime, message, TtlQueueConfig.QUEUE_TTL_C);
        rabbitTemplate.convertAndSend(TtlQueueConfig.EXC_TTL, "key_ttl_c", message,
                (msg)-> {
                    msg.getMessageProperties().setExpiration(ttlTime);
                    return msg;
                });
    }


    // 开始发消息 基于插件的延时队列  消息 延时时间
    @GetMapping("/sendDelayedMsg/{message}/{delayedTime}")
    public void sendMsg(@PathVariable String message, @PathVariable Integer delayedTime){
        logger.info("当前时间：{}, 发送一条时长为 {}ms的消息给延时队列 ==> {}", new Date(), delayedTime, message);
        rabbitTemplate.convertAndSend(
                DelayedQueueConfig.DELAYED_EXCHANGE,
                DelayedQueueConfig.DELAYED_ROUTING_KEY,
                message,
                (msg)-> {
                    msg.getMessageProperties().setDelay(delayedTime);
                    return msg;
                });
    }

}